﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarController : MonoBehaviour 
{
	[HideInInspector]public GameObject targetCanvas;
	public GameObject healthBarPrefab;
	public GameObject hitSplatPrefab;
	[HideInInspector]public GameObject avatar;
	public GameObject currentHealthBar;
	private HealthBar hb;
	private float lastHealthPercent;
	void Awake()
	{
		lastHealthPercent = 1.1F;
	}

	public void SetHealth(float percent)
	{	
		SetCanvas();
		if (percent<lastHealthPercent)
		{
			if (currentHealthBar == null)
			{
				MakeHealthBar();
			}
			hb.SetHealth(percent);

		} else
		{
			if (currentHealthBar != null)
			{
				hb.SetHealth(percent);
			}
		}
		lastHealthPercent = percent;
	}
	public void HitSplat(int damage)
	{	
		SetCanvas();
		GameObject hitSplatObj =  GameObject.Instantiate(hitSplatPrefab,avatar.transform.position,Quaternion.identity);
		hitSplatObj.transform.SetParent(targetCanvas.transform);
		HitSplat hitSplat = hitSplatObj.GetComponent<HitSplat>();
		hitSplat.SetDamage(damage);
		hitSplat.affected = avatar.transform;
	}
	void MakeHealthBar()
	{
		currentHealthBar = GameObject.Instantiate(healthBarPrefab,avatar.transform.position,Quaternion.identity);
		hb = currentHealthBar.GetComponent<HealthBar>();
		hb.player = avatar.transform;
		hb.transform.SetParent(targetCanvas.transform);
	}
	public void CloseTo(GameObject deadAvatar)
	{	

		if (hb!=null)
		{
			hb.player = deadAvatar.transform;
		}
		HitSplat[] hitSplats = GameObject.FindObjectsOfType<HitSplat>();
		foreach (HitSplat h in hitSplats)
		{
			if (h.affected == avatar.transform)
			{
				h.affected = deadAvatar.transform;
			}
		}
		avatar = deadAvatar;
	}

	void SetCanvas()
	{
		if (targetCanvas == null)
		{
				targetCanvas = GameManager.instance.uiManager.playCanvas;
		}
	}
	
}
